import Vue from 'vue'
import VueRouter from 'vue-router'
import HomeView from '../views/HomeView.vue'
import store from '../store'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: 'layout',
    component: () => import('../layout/index.vue'),
    // redirect: '/home',
    children: [
      {
        path: 'cart',
        name: 'cart',
        meta: {
          auth: true,
          title: '购物车',
        },
        component: () => import('../views/Cart.vue'),
      },
      {
        path: 'about',
        name: 'about',
        component: () => import('../views/AboutView.vue'),
      },
    ],
  },
  {
    path: '/login',
    name: 'login',
    meta: {
      title: '登陆',
    },
    component: () => import('../views/Login.vue'),
  },
  {
    path: '/home',
    name: 'home',
    meta: {
      auth: false,
      title: '首页',
    },
    component: HomeView,
  },
  {
    path: '/detail/:id',
    name: 'detail',
    meta: {
      title: '详情',
    },
    component: () => import('../views/Detail.vue'),
  },

  {
    path: '*',
    component: () => import('../views/404.vue'),
  },
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes,
})

router.beforeEach((to, from, next) => {
  if (to.name === 'login') {
    next()
  } else {
    console.log('需要守卫：', to.meta.auth)
    if (to.meta.auth) {
      const token = store.state.token
      if (token) {
        console.log('token:', token)
        next()
      } else {
        next('/login')
      }
    } else {
      next()
    }
  }
})

export default router
